$(function(){

    AGE._setHtmlUsername();

    $('.lazyload').lazyload();

    AGE.history.init();

    const usernameInput = document.getElementById('form-username-input');
    const loginModalEl = document.getElementById('loginModal');
    const loginModal = new bootstrap.Modal('#loginModal', {
        keyboard: false,
        backdrop: 'static'
    });

    $("#btnLogAndReg, #btnNeedLogin").click(function(){
        loginModal.show();
    });

    loginModalEl.addEventListener('shown.bs.modal', event => {
        usernameInput.focus();
    })

    // 注册和登录切换
    $("#loginModal .switch-btn").click(function() {
        if ($(this).hasClass("active")) return;
        if($("#input-repassword-group").is(":hidden"))
        {
            $("#loginForm").data("action", "reg");
            $(".switch-btn").removeClass("active");
            $("#reg-btn-label").addClass("active");
            $("#input-repassword-group").css("display", "flex");
        } else {
            $("#loginForm").data("action", "login");
            $(".switch-btn").removeClass("active");
            $("#log-btn-label").addClass("active");
            $("#input-repassword-group").hide();
        }
    });

    var captchaImgEl = $("#captcha-Image");
    $("#loginModal input[name='form-captcha']").one("focus", function(){
        var url = captchaImgEl.data("url") + "?_t=" + parseFloat(new Date().getTime() / 1000) + "";
        captchaImgEl.attr("src", url).css("visibility", "visible");
    });

    captchaImgEl.click(function(){
        var url = captchaImgEl.data("url") + "?_t=" + parseFloat(new Date().getTime() / 1000) + "";
        captchaImgEl.attr("src", url);
    });

    $("#loginForm").submit(function(e){

        let action = $(this).data("action");
        let btnEl = $("#btnLoginAndReg");

        e.preventDefault();
        e.stopPropagation();

        let params = {};
        let password = $(this).find("input[name='form-password']").val();
        let repassword = $(this).find("input[name='form-repassword']").val();
        let username = $(this).find("input[name='form-username']").val();
        let captcha = $(this).find("input[name='form-captcha']").val();

        if (password === "" || username === "" || captcha === "") {
            $(this).find(".tips").text("用户名、密码、验证码不能为空！").removeClass("success").addClass("failed").show();
            return;
        }

        if (username.length > 16) {
            $(this).find(".tips").text("用户名长度限制 16 个字符！").removeClass("success").addClass("failed").show();
            return;
        }

        if (password.length < 8 || password.length > 32) {
            $(this).find(".tips").text("密码长度限制 8-32 个字符！").removeClass("success").addClass("failed").show();
            return;
        }

        if (captcha.length !== 4) {
            $(this).find(".tips").text("验证码不正确").removeClass("success").addClass("failed").show();
            return;
        }

        params = {
            'username' : username,
            'password' : password,
            'captcha' : captcha,
            'action' : action
        };

        if (action === "reg")
        {
            if (repassword === "") {
                $(this).find(".tips").text("重复密码不能为空！").removeClass("success").addClass("failed").show();
                return;
            }
            if (repassword !== "" && password !== repassword) {
                $(this).find(".tips").text("两次密码不相同！").removeClass("success").addClass("failed").show();
                return;
            }
            params.repassword = repassword;
        }

        $(this).find(".tips").hide();
        btnEl.addClass("disabled").html('<span class="spinner-border spinner-border-sm"></span> 加载中...');

        $.ajax({
            type: 'POST',
            url:  '/api/account/login',
            data:  params,
            dataType: 'json',
            success: (ret) => {
                // 这里根据实际情况,来提示 form 表单
                if (ret.code !== 200) {
                    var url = captchaImgEl.data("url") + "?_t=" + parseFloat(new Date().getTime() / 1000) + "";
                    captchaImgEl.attr("src", url);

                    btnEl.removeClass("disabled").html("提交");
                    $(this).find(".tips").text(ret.message).removeClass("success").addClass("failed").show();
                } else {
                    AGE._setHtmlUsername();
                    loginModal.hide();
                }
            }
        });
    });

    $("#collectBtn").click(function(){

        if (AGE.isLogin !== 1) {
            loginModal.show();
            return;
        }

        var collectBtnEl = $(this);
        var status = collectBtnEl.attr("node-data-status");
        var id = collectBtnEl.attr("node-data-id");
        $.ajax({
            type: 'POST',
            url: '/api/collect',
            dataType: 'json',
            data: {
                'id' : id,
                'status' : status,
                'action' : "collect"
            },
            success : (ret) =>
            {
                if (ret.code !== 200)
                {
                    alert(ret.message);
                    return;
                }

                if (ret.data.status === 1)
                {
                    collectBtnEl.attr("node-data-status", 1);
                    collectBtnEl.find("i").removeClass("bi-heart").addClass("bi-heart-fill");
                    collectBtnEl.find("span").text(" 已收藏");
                }
                else
                {
                    collectBtnEl.attr("node-data-status", 0);
                    collectBtnEl.find("i").removeClass("bi-heart-fill").addClass("bi-heart");
                    collectBtnEl.find("span").text("");
                }

            }
        });
    });

    $(".video-item-cancel-fav").click(function(){
        var collectBtnEl = $(this);
        var status = collectBtnEl.attr("node-data-status");
        var id = collectBtnEl.attr("node-data-id");
        $.ajax({
            type: 'POST',
            url: '/api/collect',
            dataType: 'json',
            data: {
                'id' : id,
                'status' : status,
                'action' : "collect"
            },
            success : (ret) =>
            {
                if (ret.code !== 200) {
                    alert(ret.message);
                    return;
                }

                var itemDom = collectBtnEl.parentsUntil(".video_item").parent().parent();
                itemDom.remove();
            }
        });
    });

    $("#resetPasswordForm").submit(function(e){
        e.preventDefault();

        const tipsEl = $(this).find(".tips");
        const old_password = $(this).find("input[name='form-reset-oldpassword']").val();
        const new_password = $(this).find("input[name='form-reset-newpassword']").val();
        const re_password = $(this).find("input[name='form-reset-repassword']").val();
        let btnEl = $("#btnPasswordChange");

        if (old_password === "" || new_password === "" || re_password === "") {
            tipsEl.removeClass("success").addClass("failed").text("密码不能为空!").show();
            return;
        }

        if (new_password !== re_password) {
            tipsEl.removeClass("success").addClass("failed").text("两次密码不相同!").show();
            return;
        }

        btnEl.addClass("disabled").html('<span class="spinner-border spinner-border-sm"></span> 加载中...');
        $.ajax({
            type: 'POST',
            url: '/api/account/password',
            dataType: 'json',
            data: {
                'oldpassword' : old_password,
                'newpassword' : new_password,
                'repassword' : re_password,
                'action' : "resetpassword"
            },
            success : (ret) =>
            {
                if (ret.code === 200) {
                    tipsEl.removeClass("failed").addClass("success").text("重置密码成功!").show();
                } else {
                    tipsEl.removeClass("success").addClass("failed").text(ret.message).show();
                }
                btnEl.removeClass("disabled").html("提交");
            }
        });
    });

    $(window).scroll(function(){
        var h = $(document).scrollTop();
        if (h > 500) {
            $("#side-tools-gototop").fadeIn();
        } else {
            $("#side-tools-gototop").fadeOut();
        }
    });

    $("body").on("click", "#side-tools-gototop", function(){
        $(window).scrollTop(0);
    });

    $(".rank_list_select").on("change", function () {
        let year = $(this).val();
        let url = year == "all" ? "/rank" : "/rank?year=" + year;
        window.location.href = url;
    });
});
